import React, { Component } from "react";
import BaseComponent from "@/components/BaseComponent";
import { Button, Col, Popconfirm, Row, Upload } from "antd";
import { attachmentPrefixUrl } from "@/defaultSettings";

/**
 * 附件上传
 */
class FileUploader extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      fileList: []
    };
  }

  /**
   * 赋值
   * @param values
   */
  setFieldsValue(values) {
    if (values) {
      this.setState({
        fileList: JSON.parse(values)
      });
    }
  }

  /**
   * 返回用户输入
   * @returns {*}
   */
  getUserInput = () => {
    const { fileList } = this.state;
    return fileList.map(item => {
      const { name, filePath, url, attachmentId } = item;
      return {
        name,
        filePath,
        url,
        attachmentId
      };
    });
  };

  render() {
    const { disabled } = this.props;
    return (
      <Row>
        <Col span={10}>
          <div className={"l3Input"}>
            <span>附件列表:</span>
          </div>
        </Col>
        <Col
          span={14}
          className={"colItem"}
          style={{ display: "flex", justifyContent: "flex-end" }}
        >
          {disabled ? null : (
            <Upload
              showUploadList={false}
              action={"/api/file/file/uploadCerAttachmentFile"}
              beforeUpload={this.handleUploadBefore}
              onChange={info => {
                this.handleUploadChange({ info });
              }}
            >
              <Button type="default">上传附件</Button>
            </Upload>
          )}
        </Col>
        <Col span={24}>
          <div>
            {this.state.fileList.map((item, index) => {
              return (
                  <div
                      key={index}
                      style={{ display: "flex", alignItems: "center" }}
                  >
                    {item.isUploading ? (
                        <span>{`${index + 1}.${item.name}`}</span>
                    ) : (
                        <a
                            href={"javascript:;"}
                            onClick={() => {
                              const url = `${attachmentPrefixUrl}${item.url}`;
                              window.open(url);
                            }}
                        >
                          {`${index + 1}.${item.name}`}
                        </a>
                    )}
                    {!disabled ? (
                        <div style={{ flex: "1", textAlign: "right" }}>
                          {item.isUploading ? (
                              <div>
                                <span style={{ marginRight: "8px" }}>上传中...</span>
                                <Popconfirm
                                    title="确定删除吗?"
                                    onConfirm={() => {
                                      this.handleDelClick(index);
                                    }}
                                >
                                  <Button type={"link"} style={{ color: "#E94737" }}>
                                    删除
                                  </Button>
                                </Popconfirm>
                              </div>
                          ) : (
                              <Popconfirm
                                  title="确定删除吗?"
                                  onConfirm={() => {
                                    this.handleDelClick(index);
                                  }}
                              >
                                <Button type={"link"} style={{ color: "#E94737" }}>
                                  删除
                                </Button>
                              </Popconfirm>
                          )}
                        </div>
                    ) : null}
                  </div>
              );
            })}
          </div>
        </Col>
      </Row>
    );
  }

  handleUploadBefore = file => {
    this.setState({ isUploading: true }, () => {
      this.hide = this.loadingMessage("正在上传...");
    });

    const { fileList } = this.state;
    const obj = {
      name: file.name,
      type: file.type,
      isUploading: true
    };
    fileList.push(obj);
    this.setState({ fileList });

    return true;
  };

  handleUploadChange = ({ info, index }) => {
    if (info.file.status !== "uploading") {
    }
    if (info.file.status === "done") {
      const response = info.file.response;
      const {
        data: { filePath, attachmentId, originalFilename }
      } = response;
      if (filePath) {
        const arr = filePath.split("/");
        // 文件前缀
        const prefix = arr[arr.length - 3] + "/" + arr[arr.length - 2];
        // 文件的访问路径
        const url = `${prefix}/${originalFilename}`;
        const { fileList } = this.state;
        const obj = fileList.find(each => each.name == info.file.name);
        //上传完成
        if (obj) {
          obj.isUploading = false;
          obj.url = url;
          obj.filePath = filePath;
          obj.attachmentId = attachmentId;
          obj.key = this.generateId();
        }
        this.setState({
          fileList: [...fileList]
        });
      }

      if (this.hide) {
        this.hide();
      }
      this.successMessage("上传成功");
    } else if (info.file.status === "error") {
      this.errorMessage("文件上传出错,请联系管理员");
    }
  };

  handleDelClick = index => {
    const { fileList } = this.state;
    fileList.splice(index, 1);
    this.setState({
      fileList: [...fileList]
    });
  };
}

export default FileUploader;
